package plugins.detail;

import com.alibaba.dubbo.common.utils.StringUtils;
import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.ext.form.container.MessageCarouselContainer;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.control.events.ClickEvent;
import kd.bos.form.control.events.ClickListener;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.control.events.ItemClickListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.url.UrlService;
import kd.sdk.plugin.Plugin;

import java.math.BigDecimal;
import java.util.*;

/**
 * 动态表单插件 - 新闻轮播
 */
public class NewsCarousel extends AbstractFormPlugin implements Plugin {
    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        loadNewsToCarousel();
    }

    private void loadNewsToCarousel() {
        // 1. 获取轮播容器控件
        MessageCarouselContainer carousel =
                (MessageCarouselContainer) this.getView().getControl("dcb4_messagecarouselconta");

        // 2. 查询最新4条新闻
        String entityName = "dcb4_news";
        String selectFields = "dcb4_showpicture,dcb4_title";
        QFilter[] filters = new QFilter[0];
        String orderBy = "billno desc";
        int top = 4;

        // 直接获取数组并遍历
        DynamicObject[] newsArray =
                BusinessDataServiceHelper.load(entityName, selectFields, filters, orderBy, top);

        if (newsArray == null || newsArray.length == 0) {
            return;
        }

        // 构造轮播数据
        List<Map<String, Object>> carouselData = new ArrayList<>();
        for (DynamicObject news : newsArray) {
            Map<String, Object> item = new HashMap<>();

            // 图片控件数据 - 关键转换
            Map<String, Object> imageProps = new HashMap<>();
            String localImagePath = news.getString("dcb4_showpicture");

            if (localImagePath != null && !localImagePath.isEmpty()) {
                // 将本地路径转换为完整URL
                String imageFullUrl = UrlService.getImageFullUrl(localImagePath);
                imageProps.put("imageKey", imageFullUrl);
            } else {
                // 设置默认图片或留空
                imageProps.put("imageKey", "");
            }

            item.put("dcb4_imageap2", imageProps);

            // 文本控件数据
            Map<String, Object> textProps = new HashMap<>();
            textProps.put("text", news.getString("dcb4_title"));
            item.put("dcb4_labelap", textProps);

            carouselData.add(item);
        }

        // 4. 注入数据到轮播容器
        carousel.setData(carouselData);
    }
}

